package com.huidu.bitrade.controller.businessRealization;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.huidu.bitrade.constant.*;
import com.huidu.bitrade.entity.*;
import com.huidu.bitrade.service.*;
import com.huidu.bitrade.vo.OtcBusinessRealizationVO;
import com.querydsl.core.types.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.huidu.bitrade.controller.BaseController;
import com.huidu.bitrade.util.MessageResult;
import com.fasterxml.jackson.annotation.JsonFormat;


/**
 * otc商家变现
 */
@RestController
@RequestMapping("business/withdraw")
public class OtcBusinessRealizationController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(OtcBusinessRealizationController.class);

    @Autowired
    private OtcBusinessRealizationService businessRealizationService;
    @Autowired
    private LocaleMessageSourceService msService;
    @Autowired
    private MemberWalletService memberWalletService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberTransactionService memberTransactionService;
    /**
     * 分页查询商家变现申请
     */
    @PostMapping("page-query")
    public MessageResult pageQuery(
            PageModel pageModel,
            @RequestParam(value = "account", required = false) String account,
            @RequestParam(value = "status", required = false) Integer status,
            @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd") Date startDate,
            @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd") Date endDate) {
        List<Predicate> predicates = new ArrayList<>();
        predicates.add(QOtcBusinessRealization.otcBusinessRealization.memberId.eq(QMember.member.id));
        if (!StringUtils.isEmpty(account)) {
            predicates.add(QMember.member.username.like("%" + account + "%")
                    .or(QMember.member.mobilePhone.like("%" + account + "%"))
                    .or(QMember.member.email.like("%" + account + "%"))
                    .or(QMember.member.realName.like("%" + account + "%")));
        }
        if (status != null) {
            predicates.add(QOtcBusinessRealization.otcBusinessRealization.status.eq(status));
        }
        if (startDate != null) {
            predicates.add(QOtcBusinessRealization.otcBusinessRealization.createTime.goe(startDate));
        }
        if (endDate != null) {
            predicates.add(QOtcBusinessRealization.otcBusinessRealization.createTime.loe(endDate));
        }

        Page<OtcBusinessRealizationVO> page = businessRealizationService.joinFind(predicates, pageModel);
        return success(page);
    }


    /**
     * 商家承兑变现审核
     */
    @PostMapping("audit")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult audit(
            @RequestParam(value = "id") Long id,
            @RequestParam(value = "success") BooleanEnum success,
            @RequestParam(value = "reason", required = false) String reason
    ) {
        OtcBusinessRealization businessRealization = businessRealizationService.findOne(id);
        if (businessRealization == null) {
            return error("数据不存在");
        }
        if (businessRealization.getStatus() != OtcBusinessConstants.WITHDRAW_AUDIT_WAIT) {
            return error("申请不是待审状态");
        }
        Long memberId = businessRealization.getMemberId();
        businessRealization.setAuditTime(new Date());
        //审核通过
        if (success == BooleanEnum.IS_TRUE) {
            Member member = memberService.findOne(memberId);
            //承兑保证金
            BusinessDepositStrategy strategy = member.getBusinessDepositStrategy();
            if (strategy == null || strategy.getStatus() == CommonStatus.ILLEGAL) {
                return error("保证金策略不可用");
            }
            //查询今日已用额度
            BigDecimal todayAmount = businessRealizationService.findTodayAmount(businessRealization.getMemberId(), OtcBusinessConstants.WITHDRAW_ACCEPT_SUCCESS);
            if (todayAmount.compareTo(strategy.getDailyAmount()) > 0) {
                return error("超出每日限额,无法通过");
            }
            //通过
            businessRealization.setStatus(OtcBusinessConstants.WITHDRAW_AUDIT_SUCCESS);//审核成功
            businessRealizationService.save(businessRealization);
            return MessageResult.success(msService.getMessage("PASS_THE_AUDIT"));
        } else {
            //审核不通过
            businessRealization.setStatus(OtcBusinessConstants.WITHDRAW_AUDIT_FAIL);
            businessRealization.setReason(reason);
            businessRealizationService.save(businessRealization);
            //冻结解冻增加余额
            MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId(OtcBusinessConstants.DEFAULT_UNIT, memberId);
            memberWalletService.thawBalance(memberWallet,businessRealization.getAmount());
        }
        return MessageResult.success(msService.getMessage("AUDIT_DOES_NOT_PASS"));
    }


    /**
     * 上传凭证承兑
     */
    @PostMapping("acceptance")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult acceptance(
            @RequestParam(value = "id") Long id,
            @RequestParam(value = "image") String image
    ) {
        OtcBusinessRealization businessRealization = businessRealizationService.findOne(id);
        if (businessRealization == null) {
            return error("数据不存在");
        }
        if (businessRealization.getStatus() != OtcBusinessConstants.WITHDRAW_AUDIT_SUCCESS) {
            return error("申请不是等待承兑状态");
        }
        Member member = memberService.findOne(businessRealization.getMemberId());
        BusinessDepositStrategy strategy = member.getBusinessDepositStrategy();
        if (strategy == null || strategy.getStatus() == CommonStatus.ILLEGAL) {
            return error("保证金策略不可用");
        }
        if (StringUtils.isEmpty(image)) {
            return error("请上传支付凭证");
        }
        //查询今日已用额度
        BigDecimal todayAmount = businessRealizationService.findTodayAmount(businessRealization.getMemberId(), OtcBusinessConstants.WITHDRAW_ACCEPT_SUCCESS);
        if (todayAmount.compareTo(strategy.getDailyAmount()) > 0) {
            return error("超出每日限额,无法承兑");
        }
        //通过
        businessRealization.setImage(image);//支付凭证
        businessRealization.setStatus(OtcBusinessConstants.WITHDRAW_ACCEPT_SUCCESS);//成功
        businessRealization.setPayTime(new Date());//打款时间;
        businessRealizationService.save(businessRealization);
        //减冻结余额
        MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId(OtcBusinessConstants.DEFAULT_UNIT, businessRealization.getMemberId());
        memberWalletService.decreaseFrozen(memberWallet.getId(),businessRealization.getAmount());
        //保存交易流水
        memberTransactionService.saveBusinessMemberTransaction(businessRealization.getAmount(), TransactionType.MERCHANT_BAIL_WITHDRAW, businessRealization.getMemberId());
        return MessageResult.success("操作成功");

    }


}
